// ContactDialog.cs
//
//  Copyright (C) 2008 Jacek Trubłajewicz
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//

using System;
using System.Drawing;
using System.IO;
using Mono.Unix;
using NLog;

namespace wxGadu
{
	
	public class ContactInfoDialog : ContactDialog
	{
		#region Id
		protected enum Id
		{
		}
		#endregion

		#region controls
		protected wx.Button updateButton;
		protected wx.Button cancelButton;
		#endregion
		
		#region data members
		protected ContactInfo contactData;
#if LOG
		private Logger logger = LogManager.GetCurrentClassLogger();
#endif
		private bool uinChanged;
		#endregion

		public ContactInfoDialog(wx.Window parent, int id, string title, Point pos, Size size, uint style, ContactInfo contactData):
			base(parent, id, title, pos, size, style)
		{		
			this.contactData = contactData;
			
			updateButton = new wx.Button(this, wx.Window.wxID_OK, Catalog.GetString("Update"));
			cancelButton = new wx.Button(this, wx.Window.wxID_CANCEL, Catalog.GetString("Cancel"));
			DoLayout();
			updateButton.ToolTip = Catalog.GetString("Update information about this contact");
			cancelButton.ToolTip = Catalog.GetString("Close this window without saving any changes");
			EVT_CLOSE(new wx.EventListener(OnWindowClose));
		}


		private void DoLayout()
		{
			buttonSizer.Add(updateButton, 0, wx.Direction.wxRIGHT|wx.Direction.wxBOTTOM, 5);
			buttonSizer.Add(cancelButton, 0, wx.Direction.wxLEFT|wx.Direction.wxRIGHT|wx.Direction.wxBOTTOM, 5);
		}
		
		public override bool TransferDataToWindow()
		{
#if LOG
			logger.Trace(String.Format(Catalog.GetString("ContactInfoDialog window opend for UIN: {0}"), contactData.Uin));
#endif
			
			if (!(contactData is ContactInfo))
			{
				//TODO: log this warning
				wx.MessageDialog md = new wx.MessageDialog(this, 
				                                           Catalog.GetString("User information not available.\nThis should not happen."), 
				                                           Catalog.GetString("Empty user data"), 
				                                           wx.MessageDialog.wxICON_EXCLAMATION|wx.MessageDialog.wxOK
				                                           );
			}
			
			ggTC.Value = contactData.Uin.ToString();
			nameTC.Value = contactData.Name;
			firstNameTC.Value = contactData.Firstname;
			lastNameTC.Value = contactData.Lastname;
			locationTC.Value = contactData.Location;
			phoneTC.Value = contactData.Phone;
			
			string path = mainFrame.AppCfg.AvatarsDir + Path.DirectorySeparatorChar + contactData.Uin + ".jpg";
			if (File.Exists(path))
			{
				try
				{
					photoButton.BitmapLabel = new wx.Bitmap(Helper.LoadAndScale(path, 96));
				}
				catch (ArgumentException e)
				{
					wx.MessageDialog md = new wx.MessageDialog(this, e.Message, Catalog.GetString("File not loaded"),
			                                           wx.MessageDialog.wxOK|wx.MessageDialog.wxICON_ERROR);
					md.ShowModal();
				}
			}
			
			return true;
		}
		
		public override bool TransferDataFromWindow()
		{
			if (ggTC.Value == String.Empty)
			{
				wx.MessageDialog md = new wx.MessageDialog(this, Catalog.GetString("GG field cannot be empty"), Catalog.GetString("Empty field"),
			                                           wx.MessageDialog.wxOK|wx.MessageDialog.wxICON_EXCLAMATION);
				md.ShowModal();
				
				return false;
			}
			int val;
			if (!Int32.TryParse(ggTC.Value, out val))
			{
				wx.MessageDialog md = new wx.MessageDialog(this, Catalog.GetString("GG field must contain only numeric values"), Catalog.GetString("Illegal value"),
			                                           wx.MessageDialog.wxOK|wx.MessageDialog.wxICON_EXCLAMATION);
				md.ShowModal();
				
				return false;
			}
						
			if (nameTC.Value == String.Empty)
			{
				wx.MessageDialog md = new wx.MessageDialog(this, Catalog.GetString("Name field cannot be empty"), Catalog.GetString("Empty field"),
			                                           wx.MessageDialog.wxOK|wx.MessageDialog.wxICON_EXCLAMATION);
				md.ShowModal();
				
				return false;
			}
			//TODO: this whole part need more work
			// when uin change we need to inform Gadu.Users
			// and proxy list ctrl about change
			// we need to update ContactManger.Contacts and contacts file
			// also bottom panel need to be updated 
			// THIS IS DONE (I THINK)
			//check if contact UIN changed
			if (contactData.Uin != Int32.Parse(ggTC.Value) || contactData.Name != nameTC.Value)
			{
				// copy information into new object
				ContactInfo newContactData = new ContactInfo();
				newContactData.Uin = Int32.Parse(ggTC.Value);
				newContactData.Name = nameTC.Value;
				newContactData.Firstname = firstNameTC.Value;
				newContactData.Lastname = lastNameTC.Value;
				newContactData.Location = locationTC.Value;
				newContactData.Phone = phoneTC.Value;
				
				// save new avatars
				string path = mainFrame.AppCfg.AvatarsDir + Path.DirectorySeparatorChar + newContactData.Uin + ".jpg";
				try
				{
					photoButton.BitmapLabel.SaveFile(path, wx.BitmapType.wxBITMAP_TYPE_JPEG);
					contactData.Photo = photoButton.BitmapLabel;
					contactData.PhotoSmall = new wx.Bitmap(Helper.LoadAndScale(photoButton.BitmapLabel.ConvertToImage(), 80));
				}
				catch (ArgumentException)
				{		
#if LOG
					logger.Error(String.Format(Catalog.GetString("Bottom panel photo not resized correctly")));
#endif
				}
				
				// call Dispatcher method which updates what is needed
				mainFrame.Dispatch.ContactUinNameChanged(newContactData, contactData.Uin);
			}
			else
			{
				// simple update contactData fields and write data to file
				contactData.Firstname = firstNameTC.Value;
				contactData.Firstname = firstNameTC.Value;
				contactData.Lastname = lastNameTC.Value;
				contactData.Location = locationTC.Value;
				contactData.Phone = phoneTC.Value;
				
				string path = mainFrame.AppCfg.AvatarsDir + Path.DirectorySeparatorChar + contactData.Uin + ".jpg";

				try
				{
					photoButton.BitmapLabel.SaveFile(path, wx.BitmapType.wxBITMAP_TYPE_JPEG);
					contactData.Photo = photoButton.BitmapLabel;
					contactData.PhotoSmall = new wx.Bitmap(Helper.LoadAndScale(photoButton.BitmapLabel.ConvertToImage(), 80));
				}
				catch (ArgumentException)
				{		
#if LOG
					logger.Error(String.Format(Catalog.GetString("Bottom panel photo not resized correctly")));
#endif
				}
				
				// update contact data in contacts file 
				mainFrame.Dispatch.ContactMgr.UpdateContactInFile(contactData.Uin);
				
				// now update bottom panel
				mainFrame.BottomWindow.DisplayContactInfo(contactData.Uin);
			}	
			
			return true;
		}
		
		private void OnWindowClose(object sender, wx.Event evt)
		{
			mainFrame.DeleteContactInfoDialog(contactData.Uin);
			//TODO; check what is called first EVT_CLOSE or 
			// TransferDataFromWindow, if TDFW and user change
			//contact uin than ...
		}
	}
}
